package editor.tester;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;

import org.jwalk.JWalkException;

import editor.Context;

/**
 * AbstractDialog is the abstract superclass of custom dialogs.
 * AbstractDialog is part of the JWalk Tester application.  It defines the
 * common behaviour for exiting the dialog and saving settings.
 * 
 * @author Anthony Simons
 * @version 1.0
 */
@SuppressWarnings("serial")
public abstract class AbstractDialog extends JDialog {
	

	/**
	 * Creates a custom dialog for the JWalk Tester application.
	 * Opens the dialog and uses the title as the title for the dialog.
	 * @param tester the JWalk Tester application.
	 */
	public AbstractDialog (String title) {
		super(Context.getJwalkEditor(), title, true);		// main frame, title, open on create
	}
	
	/**
	 * Creates the exit dialog panel, which contains two centred buttons
	 * "OK" and "Cancel".  If "OK" is clicked, the dialog settings are
	 * saved; otherwise if the "Cancel" button is clicked, the settings
	 * are ignored.
	 */
	protected JPanel createExitDialogPanel() {
		JPanel panel = new JPanel();
		panel.setLayout(new FlowLayout(FlowLayout.CENTER));
		JButton okButton = new JButton("OK");
		okButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent event) {
				saveSettings(true);
			}
		});
		JButton cancelButton = new JButton("Cancel");
		cancelButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent event) {
				saveSettings(false);
			}
		});
		panel.add(okButton);
		panel.add(cancelButton);
		return panel;
	}

	/**
	 * Commits the current settings of this AbstractDialog.
	 * If the "OK" button was clicked, <code>okClicked</code> is true; and if, 
	 * the "Cancel" button was clicked, <code>okClicked</code> is false.
	 * If true, then the settings of this sub-panel are uploaded to the main
	 * Settings of the JWalker test engine.  Otherwise, this dialog exits 
	 * without committing any changes.
	 * @param okClicked true, if the "OK" button was clicked; false, if the
	 * "Cancel" button was clicked.
	 */
	protected abstract void saveSettings(boolean okClicked);

	/**
	 * Prints out a more detailed description of exceptions on standard error.
	 */
	protected void logException(JWalkException ex) {
		System.err.println(ex);
		Throwable cause = ex.getCause();
		while (cause != null) {
			System.err.println("Cause: " + cause);
			cause = cause.getCause();
		}
	}


}
